package com.printeverywhere.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;

import com.printeverywhere.util.CommonUtil;

public class FileUploadServlet extends HttpServlet {

	/**  */
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(FileUploadServlet.class);


	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("doPost(HttpServletRequest, HttpServletResponse) - start"); //$NON-NLS-1$
		}

		PrintWriter out = response.getWriter();

		DiskFileUpload upload = new DiskFileUpload();
		File file = null;
		List<?> items = null;
		try {
			items = upload.parseRequest(request);
		}
		catch (FileUploadException exception) {
			logger.error(exception.getMessage());
		}
		Iterator<?> iter = items.iterator();
		while (iter.hasNext()) {
			System.out.println("test.png");
			FileItem item = (FileItem) iter.next();

			if (!item.isFormField()) {
				file = new File("test.png");
				request.getSession().setAttribute("uploadedfile", file.getAbsolutePath());
				try {
					item.write(file);
				}
				catch (Exception exception) {
					logger.error(exception);
				}
			}
		}
		if (!CommonUtil.isImage(CommonUtil.getBytesFromFile(file))) {
			request.getSession().removeAttribute("uploadedfile");
			file.delete();
			response.setContentType("text/xml");
			out.print("<?xml version='1.0' encoding='ISO-8859-1'?>");
			out.print("<msg>value</msg>");
		}


		if (logger.isDebugEnabled()) {
			logger.debug("doPost(HttpServletRequest, HttpServletResponse) - ends"); //$NON-NLS-1$
		}
	}
}
